package com.force.module.mcpclient.controller;


import com.force.module.mcpclient.service.AliClientService;
import com.force.module.mcpclient.service.impl.IFileService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
@RequestMapping("/dashScope/chatClient")
@CrossOrigin("*")
public class ChatController {

    @Autowired
    AliClientService aliClientService;

    @Autowired
    IFileService fileService;


    @RequestMapping(value = "/generateStream", method = RequestMethod.GET)
    public Flux<ChatResponse> generateStream(HttpServletResponse response, @RequestParam("id") String id, @RequestParam("prompt") String prompt) {
        response.setCharacterEncoding("UTF-8");

        return aliClientService.getClient().prompt()
                .user(prompt) // 用户输入
                .tools(aliClientService.getTools())
                .advisors(a -> a.param(MessageChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, id) // 设置对话历史记录的ID
                        .param(MessageChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)) // 设置对话历史记录的大小
                .stream()
                .chatResponse()
                .onErrorResume(e -> {
                    System.out.println("Error: " + e.getMessage());
                    return Mono.empty();
                });
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public Object uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        // 处理文件上传逻辑
        if (file.isEmpty()){
            return "文件为空";
        }
//        Path filePath = Paths.get("./uploads", file.getOriginalFilename() + System.currentTimeMillis());
        // 使用 boundedElastic 调度器来运行阻塞操作
        return fileService.dealWithFile(file);

    }
}
